package com.sk.waste.app.fragments

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.bumptech.glide.Glide
import com.lc.smc.lib.interfaces.LCInterface
import com.lc.smc.lib.utils.LCBaseUtil
import com.lc.smc.lib.utils.LCSPUtil
import com.sk.waste.app.R
import com.sk.waste.app.activitys.ClassifyActivity
import com.sk.waste.app.activitys.MainActivity
import com.sk.waste.app.activitys.ShDetailActivity
import com.sk.waste.app.activitys.SyDetailActivity
import com.sk.waste.app.activitys.VipBuyActivity
import com.sk.waste.app.adapters.MarketAdapter
import com.sk.waste.app.adapters.MerchantAdapter
import com.sk.waste.app.adapters.SliderAdapter
import com.sk.waste.app.adapters.TenderAdapter
import com.sk.waste.app.application.MyApplication
import com.sk.waste.app.bases.BaseFragment
import com.sk.waste.app.config.AppConfig
import com.sk.waste.app.config.NetWorkConfig
import com.sk.waste.app.enums.IdenEmum
import com.sk.waste.app.models.ImageModel
import com.sk.waste.app.models.MarketModel
import com.sk.waste.app.models.MaterialModel
import com.sk.waste.app.models.MerchantlModel
import com.sk.waste.app.models.NoticeModel
import com.sk.waste.app.models.TenderModel
import com.sk.waste.app.models.UserModel
import com.sk.waste.app.utils.OkHttpUtil
import com.sk.waste.app.views.MarqueeView
import com.sk.waste.app.views.MarqueeView.SCROLL_BT
import com.sk.waste.app.views.SKRecyclerView
import okhttp3.Call
import org.json.JSONObject
import java.io.IOException


/**
 * 首页
 */
class MainFragment : BaseFragment() {

    private lateinit var vpTopBanner: ViewPager2
    private lateinit var ttvPrice: TextView
    private lateinit var ttvSteel: TextView
    private lateinit var ttvYsmetals: TextView
    private lateinit var ttvHhmetals: TextView
    private lateinit var ttvJxfacility: TextView
    private lateinit var ttvKcfacility: TextView
    private lateinit var ttvElectronics: TextView
    private lateinit var ttvMaterials: TextView
    private lateinit var ttvClassifyAll: TextView
    private lateinit var skMarketPrice: MarqueeView
    private lateinit var vipImageView: ImageView
    private lateinit var skMarketPrice2: SKRecyclerView
    private lateinit var rcMerchant: SKRecyclerView
    private lateinit var rcTenderView: RecyclerView

    private var materialList = ArrayList<MaterialModel>()
    private var messages = ArrayList<NoticeModel>()
    private var marketList = ArrayList<MarketModel>()
    private lateinit var marketAdapter: MarketAdapter
    private var merchantList = ArrayList<MerchantlModel>()
    private lateinit var merchantAdapter: MerchantAdapter
    private var tenderList = ArrayList<TenderModel>()
    private lateinit var tenderAdapter: TenderAdapter
    private lateinit var uerinfo: UserModel

    override fun onCreate(savedInstanceState: Bundle?) {
        setContentView(R.layout.fragment_main)
        super.onCreate(savedInstanceState)
//        startNoticeShow()
//        startPriceAutoScroll()
        getTopBanners()
        getNoticeList()
        refreshData()
    }

    /**
     *  @time 2025/9/9  20:07
     *  @author Im_jingwei
     *  @desc 刷新数据
     */
    fun refreshData() {
//        getMaterialList()
        uerinfo = MyApplication.instance.getUserInfo()!!
        getMarketList()
        getMerchantList()
        getTenderList()
    }


    override fun findView() {
        vpTopBanner = findViewById(R.id.fg_main_top_banner) as ViewPager2
        ttvPrice = findViewById(R.id.fg_mian_price_show) as TextView
        ttvSteel = findViewById(R.id.fa_main_classify_steel) as TextView
        ttvYsmetals = findViewById(R.id.fa_main_classify_ys_metals) as TextView
        ttvHhmetals = findViewById(R.id.fa_main_classify_hh_metals) as TextView
        ttvJxfacility = findViewById(R.id.fa_main_classify_jx_facility) as TextView
        ttvKcfacility = findViewById(R.id.fa_main_classify_kc_facility) as TextView
        ttvElectronics = findViewById(R.id.fa_main_classify_electronics) as TextView
        ttvMaterials = findViewById(R.id.fa_main_classify_materials) as TextView
        ttvClassifyAll = findViewById(R.id.fg_main_classify_all) as TextView
        skMarketPrice = findViewById(R.id.fg_market_price_view) as MarqueeView
        skMarketPrice2 = findViewById(R.id.fg_market_price_recycler) as SKRecyclerView
        vipImageView = findViewById(R.id.fg_market_vip_ad) as ImageView
        rcMerchant = findViewById(R.id.fg_market_merchant_recycler) as SKRecyclerView
        rcTenderView = findViewById(R.id.fg_market_tender_recycler) as RecyclerView
    }

    public override fun setListener() {
        setClassfyListener()
        skMarketPrice2.layoutManager = LinearLayoutManager(mContext, RecyclerView.VERTICAL, false)
        marketAdapter = MarketAdapter(mContext!!, 0, marketList, null)
        skMarketPrice2.adapter = marketAdapter
        skMarketPrice2.setScrollType(1)
        skMarketPrice2.startAutoScroll()

        rcMerchant.layoutManager = LinearLayoutManager(mContext, RecyclerView.HORIZONTAL, false)
        merchantAdapter = MerchantAdapter(requireActivity(), 0, merchantList, mMerchantOnItemClickListener)
        rcMerchant.adapter = merchantAdapter
        rcMerchant.startAutoScroll()

        rcTenderView.layoutManager = LinearLayoutManager(mContext)
        tenderAdapter = TenderAdapter(requireActivity(), 0, tenderList, mTenderOnItemClickListener)
        rcTenderView.adapter = tenderAdapter

        vipImageView.setOnClickListener {
            if (!uerinfo.isVip()) {
                val intent = Intent(mContext, VipBuyActivity::class.java)
                intent.putExtra("extral_user", IdenEmum.TYPE_USER.identity)
                startActivity(intent)
            } else {
                showToastLong("敬的用户，您已经是VIP会员，会员有效期内无需重复购买！")
            }

        }

        Glide.with(requireActivity()).load(NetWorkConfig.NET_URL_IMAG_VIP).error(R.mipmap.img_vip_default).into(vipImageView);

    }

    /**
     *  @time 2025/7/2  11:23
     *  @desc 设置分类监听
     */
    private fun setClassfyListener() {

        ttvSteel.setOnClickListener {
            jumpToClassifyPage("钢铁", "1948781072144662529")
//            startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://www.njsjzr.com/#/auction-detail/1620")))
        }
        ttvYsmetals.setOnClickListener {
            jumpToClassifyPage("有色金属", "1948781216869122049")
        }
        ttvHhmetals.setOnClickListener {
            jumpToClassifyPage("混合金属", "1948781391398305794")
        }
        ttvJxfacility.setOnClickListener {
            jumpToClassifyPage("机械设备", "1948781840922836994")
        }
        ttvKcfacility.setOnClickListener {
            jumpToClassifyPage("库存物资", "1948782082275672065")
        }
        ttvElectronics.setOnClickListener {
            jumpToClassifyPage("电子电器", "1948782659479011330")
        }
        ttvMaterials.setOnClickListener {
            jumpToClassifyPage("电力物资", "1948782201209356290")
        }
        ttvClassifyAll.setOnClickListener {
            jumpToClassifyPage("", "")
        }
    }

    private fun jumpToClassifyPage(lab: String, code: String) {
        val intent = Intent(mContext, ClassifyActivity::class.java)
        intent.putExtra("extral_labname", lab)
        intent.putExtra("extral_labcode", code)
        mContext!!.startActivity(intent)
    }

    /**
     * @time 2025/4/23  18:49
     * @desc 开启轮播图
     */
    private fun startBannerView(list: ArrayList<ImageModel>) {
        val bannerAdapter = SliderAdapter(mContext!!, list)
        vpTopBanner.adapter = bannerAdapter

        val handler = Handler(Looper.getMainLooper())
        val update: Runnable = object : Runnable {
            private var page = 0 // 当前页面索引，从0开始计数
            override fun run() {
                if (list.size != 0) {
                    page = (page + 1) % list.size // 循环显示图片
//                Log.d("LCLOG", "page $page")
                    vpTopBanner.setCurrentItem(page, true) // 切换到下一项并平滑滚动
                }
                handler.postDelayed(this, 3000) // 每3秒切换一次图片
            }
        }
        handler.post(update)
    }

    /**
     *  @desc 消息通知
     */
    private fun startNoticeShow() {
        var content = ""
        for (item in messages) {
            content = content + "  " + item.content
        }
        ttvPrice.text = content
        ttvPrice.movementMethod = LinkMovementMethod.getInstance()
        ttvPrice.ellipsize = TextUtils.TruncateAt.MARQUEE
        ttvPrice.isSingleLine = true
        ttvPrice.isSelected = true
        ttvPrice.marqueeRepeatLimit = -1 // -1 表示无限循环
    }

    private fun startPriceAutoScroll() {
        skMarketPrice.isFocusable = true
        skMarketPrice.isFocusableInTouchMode = true
        skMarketPrice.setSpeed(0, 1f)
        skMarketPrice.setLineSpace(30f)
        skMarketPrice.setScrollType(SCROLL_BT)
        skMarketPrice.text =
            "1 山东铜价  1400元/吨  1500元/吨  101\n2 河北电线电缆  1400元/吨  1500元/吨  102\n3 废铁  1400元/吨  1500元/吨  103\n4 江西再生塑料  1400元/吨  1500元/吨  104"
    }

    private val mMerchantOnItemClickListener = object : LCInterface.LcCallBack {
        override fun callBack(vararg args: Any?) {
            val position = args[0] as Int
            val intent = Intent(mContext, ShDetailActivity::class.java)
            intent.putExtra("extral_merchant", merchantList[position])
            startActivity(intent)
        }

    }

    private val mTenderOnItemClickListener = object : LCInterface.LcCallBack {
        override fun callBack(vararg args: Any?) {
            val postion = args[1] as Int
            val intent = Intent(mContext, SyDetailActivity::class.java)
            intent.putExtra("tender_id", tenderList[postion].id)
            startActivity(intent)
        }

    }

    /**
     *  @time 2024/5/7  11:29
     *  @desc 获取首页顶部轮播图
     *  @param url
     */
    private fun getTopBanners() {
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_MAIN_BANNERS
        getMainActivity().showProgress()
        val httpUtil = OkHttpUtil()
        httpUtil.httpRequestGet(url, object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                getMainActivity().cancleProgress()
                LCBaseUtil.showToast(context, "获取失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    getMainActivity().cancleProgress()
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    val code = jsonObject.getInt("code")
                    val data = jsonObject.getJSONArray("data")
                    val list = ArrayList<ImageModel>()
                    if (success) {
                        for (index in 0 until data.length()) {
                            val item = ImageModel().apply { getModelInfo(data.getJSONObject(index)) }
                            list.add(item)
                        }
                        getMainActivity().runOnUiThread { startBannerView(list) }
//                        LCLogger.d(TAG, "获取成功！,返回信息：$jsonObject")
                    } else {
                        LCBaseUtil.showToast(context, "获取失败，$msg")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    getMainActivity().cancleProgress()
                    LCBaseUtil.showToast(context, "获取失败，" + e.message)
                }
            }
        })
    }


    /**
     *  @time 2024/5/7  11:29
     *  @desc 消息通知
     *  @param url
     */
    private fun getNoticeList() {
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_MAIN_NOTICELIST
        getMainActivity().showProgress()
        val httpUtil = OkHttpUtil()
        httpUtil.httpRequestGet(url, object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                LCBaseUtil.showToast(context, "获取失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    val code = jsonObject.getInt("code")
                    val data = jsonObject.getJSONArray("data")
                    messages.clear()
                    if (success) {
                        for (index in 0 until data.length()) {
                            val item = NoticeModel().apply { getModelInfo(data.getJSONObject(index)) }
                            messages.add(item)
                        }
                        activity!!.runOnUiThread { startNoticeShow() }
//                        LCLogger.d(TAG, "获取成功！,返回信息：$jsonObject")
                    } else {
                        LCBaseUtil.showToast(context, "获取失败，$msg")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    LCBaseUtil.showToast(context, "获取失败，" + e.message)
                }
            }
        })
    }


    /**
     *  @time 2024/5/7  11:29
     *  @desc 分类
     *  @param url
     */
    private fun getMaterialList() {
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_MAIN_ALLMATERIAL
        getMainActivity().showProgress()
        val httpUtil = OkHttpUtil()
        httpUtil.httpRequestGet(url, object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                LCBaseUtil.showToast(context, "获取失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    val code = jsonObject.getInt("code")
                    val data = jsonObject.getJSONArray("data")
                    materialList.clear()
                    if (success) {
                        for (index in 0 until data.length()) {
                            val item = MaterialModel().apply { getModelInfo(data.getJSONObject(index)) }
                            materialList.add(item)
                        }
                        activity?.runOnUiThread { merchantAdapter.notifyDataSetChanged() }
//                        LCLogger.d(TAG, "获取成功！,返回信息：$jsonObject")
                    } else {
                        LCBaseUtil.showToast(context, "获取失败，$msg")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    LCBaseUtil.showToast(context, "获取失败，" + e.message)
                }
            }
        })
    }

    /**
     *  @time 2024/5/7  11:29
     *  @desc 行情
     *  @param url
     */
    private fun getMarketList() {
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_MAIN_MARKET
        val token = LCSPUtil[mContext!!, AppConfig.SP_ACCESS_TOKEN]
        val params = JSONObject()
        params.put("pageSize", AppConfig.PAGE_SIZE)
        params.put("pageNo", 1)
        params.put("marketTypeCodes", "")
        params.put("productName", "")

        val httpUtil = OkHttpUtil()
        httpUtil.httpRequest(url, token, params.toString(), object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                LCBaseUtil.showToast(context, "获取失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    val code = jsonObject.getInt("code")
                    val data = jsonObject.getJSONObject("data")
                    val rows = data.getJSONArray("records")
                    marketList.clear()
                    if (success) {
                        for (index in 0 until rows.length()) {
                            val item = MarketModel().apply { getModelInfo(rows.getJSONObject(index)) }
                            marketList.add(item)
                        }
                        activity!!.runOnUiThread { marketAdapter.notifyDataSetChanged() }
//                        LCLogger.d(TAG, "获取成功！,返回信息：$jsonObject")
                    } else {
                        LCBaseUtil.showToast(context, "获取失败，$msg")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    LCBaseUtil.showToast(context, "获取失败，" + e.message)
                }
            }
        })
    }

    /**
     *  @time 2024/5/7  11:29
     *  @desc 推荐商户
     *  @param url
     */
    private fun getMerchantList() {
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_MAIN_MERCHANT
        val token = LCSPUtil[mContext!!, AppConfig.SP_ACCESS_TOKEN]
        val httpUtil = OkHttpUtil()
        httpUtil.httpRequest(url, token, "", object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                LCBaseUtil.showToast(context, "获取失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    val code = jsonObject.getInt("code")
                    val data = jsonObject.getJSONArray("data")
                    merchantList.clear()
                    if (success) {
                        for (index in 0 until data.length()) {
                            val item = MerchantlModel().apply { getModelInfo(data.getJSONObject(index)) }
                            merchantList.add(item)
                        }
                        activity!!.runOnUiThread { merchantAdapter.mNotifyDataSetChanged() }
//                        LCLogger.d(TAG, "获取成功！,返回信息：$jsonObject")
                    } else {
                        LCBaseUtil.showToast(context, "获取失败，$msg")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    LCBaseUtil.showToast(context, "获取失败，" + e.message)
                }
            }
        })
    }

    /**
     *  @time 2024/5/7  11:29
     *  @desc 生意列表
     *  @param url
     */
    private fun getTenderList() {
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_MAIN_SYLIST
        val token = LCSPUtil[mContext!!, AppConfig.SP_ACCESS_TOKEN]
        val params = JSONObject()
        params.put("pageSize", 10)
        params.put("pageNo", 1)
        params.put("contentText", "")
        params.put("subcategoryIds", "")
        val httpUtil = OkHttpUtil()
        httpUtil.httpRequest(url, token, params.toString(), object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                LCBaseUtil.showToast(context, "获取失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    val code = jsonObject.getInt("code")
                    val data = jsonObject.getJSONObject("data")
                    val rows = data.getJSONArray("rows")
                    tenderList.clear()
                    if (success) {
                        for (index in 0 until rows.length()) {
                            val item = TenderModel().apply { getModelInfo(rows.getJSONObject(index)) }
                            tenderList.add(item)
                        }
                        activity!!.runOnUiThread { tenderAdapter.mNotifyDataSetChanged() }
//                        LCLogger.d(TAG, "获取成功！,返回信息：$jsonObject")
                    } else {
                        LCBaseUtil.showToast(context, "获取失败，$msg")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    LCBaseUtil.showToast(context, "获取失败，" + e.message)
                }
            }
        })
    }

    private fun getMainActivity(): MainActivity {
        return activity as MainActivity
    }


}